﻿#include "JSEngine.h"
#include <QJSEngine>
#include <QJSValue>
#include <QTextStream>
#include <QFile>

#pragma  execution_character_set("UTF-8")



void jsEngine() {

    // 创建 QJSEngine 实例
    QJSEngine engine;

    // JavaScript 脚本
    QString script = "var x = 10; var y = 20;   x + y;";

    // 执行脚本
    QJSValue result = engine.evaluate(script);

    // 检查是否有错误
    if (result.isError()) {
        qDebug() << "Error:" << result.toString();
    }
    else {
        qDebug() << "Result:" << result.toInt();
    }

}

int  readjs() {

 
    QString mesCfgFile = QCoreApplication::applicationDirPath();
    mesCfgFile = mesCfgFile + "/script.js";
    QFile file(mesCfgFile);  // 假设记事本文件名为 script.js
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件!";
        return -1;
    }

    QTextStream in(&file);
    QString script = in.readAll();  // 读取所有内容
    file.close();

    qDebug() << "脚本内容:" << script;
    QJSEngine engine;
    // 执行脚本
    MyObject myObject;
    engine.globalObject().setProperty("console", engine.newQObject(&myObject));
    QJSValue result = engine.evaluate(script);

    // 检查是否有错误
    if (result.isError()) {
        qDebug() << "Error:" << result.toString();
    }
    else {
        qDebug() << "endl";
    }


}
JSEngine::JSEngine(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);

    readjs();


}

JSEngine::~JSEngine()
{}
